//
//  PKProductMainViewController.m
//  PianKe
//
//  Created by lanou on 15/9/25.
//  Copyright (c) 2015年 李伟伟. All rights reserved.
//

#import "PKProductMainViewController.h"
#import "PKProductMainListTableViewCell.h"
#import "PKRequestManager.h"
#import "FMDatabase.h"//数据持久化第三方
#import "MJRefresh.h"


@interface PKProductMainViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *mainTableView;//主页面
@property(nonatomic,strong)NSMutableArray *dataSourceArray;//提供数据的数组
@property(nonatomic,assign)BOOL isLoading;//是否正在刷新
@property(nonatomic,strong)UILabel *loadLabel;//显示是否刷新
@property(nonatomic,strong)FMDatabase *dataBase;
@end

@implementation PKProductMainViewController

//-(UIView *)topView
//{
//    if (_topView) {
//        _topView = nil;
//    }
//    return _topView;
//}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // Do any additional setup after loading the view.
    _isLoading = NO;
    self.view.backgroundColor = [UIColor greenColor];
    self.titleLabel.text = @"良品";
    
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 70, SCREEN_WITDTH, SCREEN_HEIGHT-70)];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    _mainTableView.rowHeight = 250;
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:_mainTableView];
    _loadLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, -50, SCREEN_WITDTH, 50)];
    _loadLabel.textAlignment = NSTextAlignmentCenter;
    [_mainTableView addSubview:_loadLabel];
    
    _dataSourceArray = [NSMutableArray array];
    
    [_mainTableView registerClass:[PKProductMainListTableViewCell class] forCellReuseIdentifier:@"PKProductMainListTableViewCell"];

    [self requestData];
    
    
    //创建一个dataBase可以打开的文件，用来保存数据
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(9, 1, 1).lastObject stringByAppendingPathComponent:@"PianKe.db"];
    
    //根据路径打开文件  不存在则创建这个文件
    _dataBase = [FMDatabase databaseWithPath:filePath];
    NSLog(@"%@------------",filePath);
    
    
    //通过open这个方法打开数据库 打开成功就返回yes,失败返回NO
    if ([_dataBase open]) {
        NSLog(@"-------打开数据库成功--------");
        [_dataBase executeUpdate:@"CREATE TABLE PRODUCT (buyurl text, contentid text, title text, coverimg text)"];
    }else{
        NSLog(@"=======打开数据库失败========");
    }
    //根据查找语句查找表里面的内容
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"SELECT * FROM PRODUCT"];
    //[resultSet next]用到了类似C语言链表的东西 每一个对象都有一个属性保存了下一个对象的指针，可以通过while循环来获取到所有的查找到的对象。
    while ([resultSet next]) {
        NSString *buyurl = [resultSet stringForColumn:@"buyurl"];
        NSString *contentid = [resultSet stringForColumn:@"contentid"];
        NSString *title = [resultSet stringForColumn:@"title"];
        NSString *coverimg = [resultSet stringForColumn:@"coverimg"];
//        NSInteger *num = [resultSet intForColumn:@"num"];
        PKProductMainListModel *model = [[PKProductMainListModel alloc]init];
        model.buyurl = buyurl;
        model.title = title;
        model.contentid = contentid;
        model.coverimg = coverimg;
        [_dataSourceArray addObject:model];
    }
    [resultSet close];
    
//    
//    self.mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self requestData];
//    }];
//    
    
    
    
    
    
}

-(void)requestData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"start"] = @"0";
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"63A94D37-33F9-40FF-9EBB-481182338873";
    parDic[@"limit"] = @"10";
    parDic[@"auth"] = @"";
    parDic[@"version"] = @"3.0.2";

   [PKRequestManager requestWithType:POST urlString:@"http://api2.pianke.me/pub/shop" parDic:parDic finish:^(NSData *data) {
       [_dataBase executeUpdate:@"DELETE FROM PRODUCT"];
       
       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
       NSArray *listArray = dic[@"data"][@"list"];
       
       [_dataSourceArray removeAllObjects];//--------------------------重要----------------

       
              for (NSDictionary *modelDic in listArray) {
           PKProductMainListModel *model = [[PKProductMainListModel alloc]init];
           [model setValuesForKeysWithDictionary:modelDic];
           [_dataSourceArray addObject:model];
           
           
           [_dataBase executeUpdate:@"INSERT INTO PRODUCT(buyurl,contentid,title,coverimg) VALUES(?,?,?,?)",model.buyurl,model.contentid,model.title,model.coverimg];//每获取一个model 都添加到数据库
       }
       
       [_mainTableView reloadData];
//       _loadLabel.text = @"刷新成功";
//       _isLoading = NO;
       [self.mainTableView.header endRefreshing];
   }
  error:^(NSError *error) {
       NSLog(@"良品请求失败 ----%@",error) ;
   }];
 
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"%f",scrollView.contentOffset.y );
    CGFloat scrollViewY = scrollView.contentOffset.y;
    //判断是否被拖拽
    if (scrollView.isDragging)
    {
        if (scrollView.contentOffset.y < 0 && scrollView.contentOffset.y > -50)
        {
            _loadLabel.text = @"再拉一点";
        }
        if (scrollViewY < -50)
        {
            _loadLabel.text = @"松手刷新";
        }
        
    } else {
            if (scrollViewY < -50 && _isLoading == NO)
            {
                _isLoading = YES;
                _loadLabel.text = @"正在刷新";
                [self requestData];
            }if (_isLoading) {
                if (scrollViewY >= -50) {
                    scrollView.contentOffset = CGPointMake(0, -50);
                }
            }
    }
    
}
    






-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PKProductMainListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PKProductMainListTableViewCell" forIndexPath:indexPath];
    cell.configureModel = _dataSourceArray[indexPath.row];
    [cell.buyButton addTarget:self action:@selector(handleBuyButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.buyButton.tag = 1000 + indexPath.row;
    return cell;
}

-(void)handleBuyButtonAction:(UIButton *)sender
{
    PKProductMainListModel *model = _dataSourceArray[sender.tag -1000];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:model.buyurl]];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [PKProductMainListTableViewCell heightForCell];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
